import { getArticleList, getCommentAdopts, getCommentDelete, getCommentList, getCommentReply } from '@/services';
import { IArticleItem, ICommentItem } from '@/types';
import { Effect, Reducer } from 'umi';

export interface ArticleModelState {
  articleList: IArticleItem[];
  articleListLength: number;
  commentList: ICommentItem[];
  commentListLength: number;
}

export interface ArticleModelType {
  namespace: 'workbench';
  state: ArticleModelState;
  effects: {
    getArticleList: Effect;
    getCommentList: Effect;
    getCommentAdopts: Effect;
    getCommentDelete: Effect;
    getCommentReply:Effect;
  };
  reducers: {
    save: Reducer<ArticleModelState>;
  };
}

const ArticleModel: ArticleModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'workbench',

  // 数据模型状态，相当于vuex的state
  state: {
    articleList: [],
    articleListLength: 0,
    commentList: [],
    commentListLength: 0,
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    *getArticleList({ payload }, { call, put, select }) {
      let result = yield call(getArticleList, payload);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            articleList: result.data[0],
            articleListLength: result.data[1],
          },
        });
      }
    },
    *getCommentList({ payload }, { call, put, select }) {
      let result = yield call(getCommentList, payload);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            commentList: result.data[0],
            commentListLength: result.data[1],
          },
        });
      }
    },
    //评论通过
    *getCommentAdopts({ payload }, { call, put, select }) {
      let result = yield call(getCommentAdopts, payload);
    },
    //评论删除
    *getCommentDelete({ payload }, { call, put, select }) {
      let result = yield call(getCommentDelete, payload);
    },
    *getCommentReply({ payload }, { call, put, select }) {
      let result = yield call(getCommentReply, payload);
    },
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default ArticleModel;
